<template>
    <div class="render">
        <Tabs 
        type="card" 
        closable 
        v-model="currentTab" 
        @on-tab-remove="removeTab"
        :animated="false" >
            <!-- 租客管理 -->
            <TabPane label="租客管理" :closable="false" :name="'0'" >
                <Row>
                    <Col span="24">
                        <Card dis-hover class="no-border-card">
                            <p slot="title">
                                租客列表
                                <Button class="btn-in-top-large" type="primary" @click="showAddModal" v-pmis="30">添加租客</Button>
                            </p>

                            <Row :gutter="14" class="yd-padding-b-16">
                                <Col span="8">
                                    <Select clearable v-model="tenant_tag_id" placeholder="请选择租客标签">
                                        <Option v-for="item in tenantTags" :value="item.id" :key="item.id">{{ item.name }}</Option>
                                    </Select>
                                </Col>
                                <Col span="8">
                                    <Select clearable v-model="selectSearchType" placeholder="查询条件">
                                        <Option v-for="item in searchTypes" :value="item.value" :key="item.value">{{ item.label }}</Option>
                                    </Select>
                                </Col>
                                <Col span="8">
                                    <Input v-model.trim="keyword" placeholder="租客姓名/手机号" icon="ios-search-strong" @on-enter="getRenterList(1)" @on-click="getRenterList(1)"/>
                                </Col>
                            </Row>
                            <Row class="yd-padding-b-16">
                                <Table class="no-btn-border" stripe border ref="selection" :columns="columns" :data="renters" :loading="isLoadig"></Table>
                            </Row>
                            <Row>
                                <Page :total="total" 
                                @on-change="getRenterList"
                                :page-size="size" 
                                :current.sync="currentPage"
                                show-elevator 
                                show-total 
                                style="text-align:center"></Page>
                            </Row>

                        </Card>
                    </Col>
                </Row>                
            </TabPane>
            <TabPane label="标签管理" :closable="false" :name="'1'">
                <Row>
                    <Col span="24">
                        <Card dis-hover class="no-border-card">
                            <p slot="title">
                                标签管理
                                <Button class="btn-in-top-large" type="primary" @click="labelShowAddModal">添加标签</Button>
                            </p>

                            <Row :gutter="14" class="yd-padding-b-16">
                                <Col span="12">
                                    <Input v-model.trim="labelName" placeholder="标签名" icon="ios-search-strong" @on-enter="getLabelList(1)" @on-click="getLabelList(1)"/>
                                </Col>
                            </Row>
                            <Row class="yd-padding-b-16">
                                <Table class="no-btn-border" stripe border ref="selection" :columns="columns2" :data="tagsDate" :loading="isLoadig"></Table>
                            </Row>
                            <Row>
                                <Page :total="labelTotal" 
                                @on-change="getLabelList"
                                :page-size="labelSize" 
                                :current.sync="currentPage"
                                show-elevator 
                                show-total 
                                style="text-align:center"></Page>
                            </Row>

                        </Card>
                    </Col>
                </Row>                
            </TabPane>
            <!-- 租客详情 -->
            <TabPane 
            v-for="(tab,index) in tabs" 
            :name="''+ tab.id" 
            :key="tab.id + index" 
            :label="tab.name" closable>
                <renterDetail :renterId="tab.id" @updateTab="updateTab" @delTab="delTab" @refreshRenterList="getRenterList(1)" @openNewTab="toRenterDetail" @openGrantRecord="openGrantRecord"></renterDetail>
            </TabPane>

            <!-- 租客授权记录 -->
            <TabPane
            v-for="(item,index) in leaseIds"
            :key="'grantRecord' + index"
            :name="item.id"
            :label="item.name" closable>
                <renterGrantRecord :leaseId="item.id" :tenantId="item.tenantId" :roomDeviceIsExistList="item.roomDeviceIsExistList"></renterGrantRecord>
            </TabPane>
        </Tabs>

        <!-- 添加租客 -->
        <Modal
            v-model="isAddModalVisible"
            :loading="true"
            :width="800"
            title="添加租客">

            <Row :guttle="40">
                <Col span="16">
                    <Form ref="addForm" :model="formItem" :rules="ruleValidate2" :label-width="110">
                        <FormItem label="租客姓名" prop="name">
                            <Input v-model="formItem.name" :maxlength="20" placeholder="租客姓名"/>
                        </FormItem>
                        <FormItem label="租客电话" prop="phone">
                            <Input v-model="formItem.phone" :maxlength="11" placeholder="租客电话">
                                <Select v-model="formItem.country_code" slot="prepend" style="width: 110px">
                                    <Option v-for="item in CountryCodes" :key="item.code" :value="item.code">{{item.country}}</Option>
                                </Select>
                            </Input>
                        </FormItem>
                        <FormItem label="身份证号" prop="id_card">
                            <Input v-model="formItem.id_card" :maxlength="18" placeholder="身份证号"></Input>
                        </FormItem>

                        <FormItem label="租客标签" prop="tenant_tag_id">
                            <Select v-model="formItem.tenant_tag_id">
                                <Option v-for="item in tenantTags" :value="item.id" :key="item.id">{{ item.name }}</Option>
                            </Select>
                        </FormItem>
                    </Form>
                </Col>

                <!-- 照片 -->
                <Col span="8" v-if="hasFaceAccessPermission">
                    <takePhoto v-model="face_file_id" :isClearPreviewImg="isClearPreviewImg"></takePhoto>
                </Col>
            </Row>

            <div slot="footer">
                <Button type="ghost" size="large" @click="cancelAddRenter('addForm')">取消</Button>
                <Button type="primary" :loading = "isLoadig" size="large" @click="confirmAddRenter('addForm')">保存</Button>
            </div>
        </Modal>

        <!-- 添加标签 -->
        <Modal
            v-model="isLabelAddModalVisible"
            :loading="true"
            :title="labelDataName.id ? '编辑标签' : '添加标签'">

            <Form ref="labelAddForm" :label-width="110">
                <FormItem label="标签名" prop="name">
                    <Input v-model="labelDataName.name" :maxlength="20" placeholder="标签名"/>
                </FormItem>
            </Form>

            <div slot="footer">
                <Button type="ghost" size="large" @click="labelCancelAddRenter()">取消</Button>
                <Button type="primary" :loading = "isLoadig" size="large" @click="labelConfirmAddRenter()">保存</Button>
            </div>
        </Modal>

        <!-- 创建租客成功 -->
        <Modal 
            v-model="isSavedModalVisible"
            :closable="false"
            ok-text="办理入住"
            cancel-text="关闭"
            @on-ok="showCheckIn">
            <Row class="renter-list-save-succ">
                <Col span="24">
                    <Icon class="icon" type="checkmark-circled"></Icon><br>
                    <span>保存成功</span>
                </Col>
            </Row>
        </Modal>

        <!-- 删除标签modal -->
        <Modal
            v-model = "isDelLabel"
            title="删除租客标签"
            @on-ok="delLabelRenter"
            @on-cancel="cancelDelLabel">
            <p>确定删除标签？标签删除后不能恢复。</p>
        </Modal>

        <!-- 租客入住 -->
        <renterCheckIn 
        v-if="isCheckInVisible"
        @cancelCheckIn="cancelCheckIn"
        @checkInSuccess="checkInSuccess"
        :renterId="currentCheckInId">
        </renterCheckIn>

    </div>

    
</template>

<script>
import validate from '@/libs/validate'
// import util from '@/libs/util';
import { http, api } from '@/libs/http'
import renterDetail from './renterDetail.vue'
import renterCheckIn from './renterCheckIn.vue'
import renterGrantRecord from './renter-grant-record.vue'
import { CountryCodes } from '@/libs/const'
import takePhoto from '../tenancy-device/take-photo'
import dayjs from 'dayjs'
import { mapState } from 'vuex'
import debounce from 'lodash/debounce'

export default {
  name: 'renterList',
  components: {
    renterDetail,
    renterCheckIn,
    renterGrantRecord,
    takePhoto
  },
  data () {
    return {
      tenant_tag_id: 0, // 租客标签id
      face_file_id: '', // 人脸face_id
      isClearPreviewImg: false, // 是否清除照片
      CountryCodes,
      tenantTags: [], // 租客标签
      currentTab: '0', // 当前Tab
      tabs: [],
      isAddModalVisible: false,
      isLabelAddModalVisible: false,
      isDelLabel: false, // 删除租客标签
      isSavedModalVisible: false,
      isCheckInVisible: false,
      leaseIds: [], // lease_id的数组
      isLoadig: false, // 是否正在发请求
      size: 20, // 分页size
      total: 0, // 分页总数
      currentPage: 1,
      keyword: '',
      searchTypes: [
        {
          value: 1,
          label: '租客姓名'
        },
        {
          value: 2,
          label: '租客手机'
        },
        {
          value: 3,
          label: '身份证'
        }
      ],
      selectSearchType: 0,
      columns: [
        // {
        //     type: 'selection',
        //     width: 60,
        //     align: 'center'
        // },
        {
          title: '姓名',
          key: 'name',
          align: 'center'
        },
        {
          title: '手机号',
          key: 'phone',
          align: 'center'
        },
        {
          title: '入住状态',
          // key: 'state',
          align: 'center',
          render: (h, params) => {
            let result = params.row.lease ? '已入住' : '无'
            return h('span', result)
          }
        },
        {
          title: '租客标签',
          align: 'center',
          render: (h, params) => {
            let result = params.row.tenant_tag && (params.row.tenant_tag.name || '')
            return h('span', result)
          }
        },
        // {
        //     title: '身份证号',
        //     key: 'id_card',
        //     align: 'center'
        // },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'ghost',
                    size: 'small'
                  },
                  // class: {
                  //     'renter-list-hide': !params.row.lease
                  // },
                  style: {
                    marginRight: '5px',
                    marginLeft: '0px'
                  },
                  on: {
                    click: () => {
                      // 打开新标签显示详情
                      let id = '' + params.row.id
                      let name = '' + params.row.name
                      this.toRenterDetail(id, name)
                    }
                  },
                  directives: [
                    {
                      name: 'pmis',
                      value: 29
                    }
                  ]
                },
                '详情'
              ),

              h(
                'Button',
                {
                  props: {
                    type: 'ghost',
                    size: 'small'
                  },
                  class: {
                    'renter-list-hide': params.row.lease
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.currentCheckInId = params.row.id
                      this.showCheckIn()
                    }
                  },
                  directives: [
                    {
                      name: 'pmis',
                      value: 30
                    }
                  ]
                },
                '入住'
              ),

              h(
                'Button',
                {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  class: {
                    'renter-list-hide': params.row.lease
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '删除租客',
                        content: '确定要删除该租客吗?',
                        okText: '确定删除',
                        onOk: () => {
                          this.delRenter(params.row.id)
                        }
                      })
                    }
                  },
                  directives: [
                    {
                      name: 'pmis',
                      value: 30
                    }
                  ]
                },
                '删除'
              )
            ])
          }
        }
      ],
      columns2: [
        {
          title: '创建人',
          key: 'create_user_name',
          align: 'center'
        },
        {
          title: '标签名',
          key: 'name',
          align: 'center'
        },
        {
          title: '创建时间',
          key: 'created_at',
          align: 'center',
          render: (h, params) => {
            let result = dayjs(params.row.created_at).format('YYYY-MM-DD HH:mm:ss')
            return h('span', result)
          }
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'ghost',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px',
                    marginLeft: '0px'
                  },
                  on: {
                    click: () => {
                      // 编辑租客标签
                      let id = params.row.id
                      let name = params.row.name
                      this.editLabelRenter(id, name)
                    }
                  }
                },
                '编辑'
              ),

              h(
                'Button',
                {
                  props: {
                    type: 'ghost',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px',
                    marginLeft: '0px'
                  },
                  on: {
                    click: () => {
                      // 删除租客标签
                      this.delLabelId = params.row.id
                      this.isDelLabel = true
                    }
                  }
                },
                '删除'
              )
            ])
          }
        }
      ],
      renters: [], // 租客列表
      tagsDate: [], // 标签列表
      isSelectAll: false,
      selectText: '全选',
      labelDataName: {
        name: '',
        id: ''
      }, // 添加的标签名
      formItem: {
        // 添加租客参数
        name: '',
        phone: '',
        id_card: '',
        country_code: '86',
        tenant_tag_id: ''
      },
      ruleValidate2: {
        name: [
          {
            required: true,
            message: '请输入租客姓名',
            trigger: 'change'
          }
        ],
        phone: [
          {
            required: true,
            message: '请输入租客手机号',
            trigger: 'change'
          },
          { validator: validate.validPhone, trigger: 'change' }
        ],
        tenant_tag_id: [
          {
            required: false
          }
        ],
        id_card: [
          {
            required: false,
            message: '请输入身份证号码',
            trigger: 'change'
          }
          // { validator: validate.validIDCard, trigger: 'blur' }
        ]
      },
      labelName: '',
      labelTotal: 0,
      labelSize: 20, // 分页size
      delLabelId: '', // 删除标签报错的id
      currentCheckInId: ''
    }
  },
  created: function () {
    if (this.$route.query.renter_id) {
      this.toRenterDetail(this.$route.query.renter_id, this.$route.query.renter_name)
    }
    if (this.$route.query.input) {
      this.keyword = this.$route.query.input
    }
    this.getRenterList(1)
    this.getLabelList(1)
    this.getTenantTag() // 获取租客标签
  },

  computed: {
    ...mapState({
      hasFaceAccessPermission: state => state.user.hasFaceAccessPermission
    })
  },

  watch: {
    tenant_tag_id (value) {
      if (value > 0) {
        this.getRenterList(1)
      }
    },

    isAddModalVisible (value) {
      if (value) {
        this.getTenantTag()
        this.isClearPreviewImg = false
      } else {
        this.isClearPreviewImg = true
        this.reset()
      }
    },

    'formItem.country_code' (value) {
      this.$set(this.ruleValidate2, 'phone', [
        {
          required: true,
          message: '请输入租客手机号',
          trigger: 'change'
        },
        { validator: value === '86' ? validate.validPhone : validate.validEnglishPhone, trigger: 'change' }
      ])
    }
  },

  methods: {
    reset () {
      this.face_file_id = ''
      this.isClearPreviewImg = true
    },

    async getTenantTag () {
      const { rows } = await http.fetch(this, api.tenant_tags_get)

      this.tenantTags = rows
    },

    /**
         * 打开授权记录
         * @param {String} leaseId
         * @param {String} roomName 房间名
         */
    openGrantRecord (leaseId, roomName, tenantId, roomDeviceIsExistList) {
      const flag = this.leaseIds.some(value => {
        return leaseId === value.id
      })

      // 如果不存在存在该leaseid的话
      if (!flag) {
        const obj = {
          id: leaseId,
          name: `房间:${roomName}-授权记录`,
          tenantId,
          roomDeviceIsExistList
        }
        this.leaseIds.push(obj)
      }

      this.currentTab = leaseId
    },

    delTab (name, del) {
      this.removeTab(name)
      this.currentTab = '0'
      this.getRenterList(1)
    },

    toRenterDetail (id, name) {
      id = String(id)

      const flag = this.tabs.some(value => {
        return id === value.id
      })

      if (!flag) {
        this.tabs.push({ id, name })
      }

      this.currentTab = id
    },

    /**
         * 移除tab
         */
    removeTab (name) {
      const pos = this.removeTabDetial(this.tabs, name)
      if (pos) {
        return
      }

      this.removeTabDetial(this.leaseIds, name)
    },

    /**
         * 删除tab具体过程
         * @param {Array} obj
         * @param {String} tabName 关闭的列表名
         * @return {Boolean} true => 表示找到已经删除的tab false => 表示循环完之后依旧没有找到要关闭的tab
         */
    removeTabDetial (arr, tabName) {
      // let { length } = arr;
      for (let i = 0; i < arr.length; i++) {
        const { id } = arr[i]

        if (id === tabName) {
          arr.splice(i, 1)
          return true
        }
      }
      return false
    },

    updateTab (id, name) {
      // 更改标签名
      let updateIndex = ''
      this.tabs.forEach((item, idx) => {
        if (item.id === id) {
          updateIndex = idx
        }
      })
      this.$set(this.tabs[updateIndex], 'name', name)
      this.getRenterList(1)
    },

    showAddModal () {
      this.isAddModalVisible = true
    },

    // 点击添加标签
    labelShowAddModal () {
      this.labelDataName.name = ''
      this.labelDataName.id = ''
      this.isLabelAddModalVisible = true
    },

    selectAll () {
      this.isSelectAll = !this.isSelectAll
      this.selectText = this.isSelectAll ? '取消全选' : '全选'
      this.$refs.selection.selectAll(this.isSelectAll)
    },

    showCheckIn () {
      this.isSavedModalVisible = false
      this.isCheckInVisible = true
    },

    delRenter (renterId) {
      http.request(this, api.tenant_del, [renterId], null, res => {
        if (res) {
          // 删除成功后刷新
          this.getRenterList(1)
        }
      })
    },

    confirmAddRenter (name) {
      // 添加租客
      if (this.isLoadig) {
        return
      }
      this.$refs[name].validate(valid => {
        if (valid) {
          let params = this.formItem

          if (this.hasFaceAccessPermission) { // 拥有门禁权限
            if (this.face_file_id) {
              params.face_file_id = this.face_file_id
            } else {
              this.$Message.error('您还没有上传照片')
              return
            }
          }

          if (!params.tenant_tag_id) {
            delete params.tenant_tag_id
          }

          if (!params.id_card) {
            delete params.id_card
          } else {
            const flag = this.validateIdCard(params.id_card) // 检验身份证号

            if (!flag) {
              this.$Message.error('请输入正确的身份证号码!')
              return
            }
          }
          if (!params.name.trim()) {
            this.$Message.error('请输入正确的姓名!')
            return
          }
          this.isLoadig = true
          http.request(this, api.tenant_create, null, params, res => {
            if (res) {
              this.isLoadig = false
              this.$Message.success('增加租客成功!')
              this.isAddModalVisible = false
              this.isSavedModalVisible = true
              this.getRenterList(1)
              this.currentCheckInId = res.tenant_id
              this.resetForm(name)
            } else {
              this.isLoadig = false
            }
          })
        } else {
          this.$Message.error('请完整填写表单数据!')
        }
      })
    },

    validateIdCard (value) {
      const reg = /(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/

      return reg.test(value)
    },

    cancelAddRenter (name) {
      // 取消添加租客
      this.resetForm(name)
      this.isAddModalVisible = false
    },

    // 请求标签列表数据
    getLabelList: debounce(function (page) {
      let params = {
        is_unopened_warn: null,
        name: this.labelName ? this.labelName : '',
        limit: this.labelSize,
        offset: this.labelSize * (page - 1)
      }
      http.request(this, api.tenant_tags_get, null, params, res => {
        if (res) {
          this.tagsDate = res.rows
          this.labelTotal = res.count || 0
        }
      })
    }, 300),

    // 关闭添加标签modal
    labelCancelAddRenter (name) {
      this.labelDataName.name = ''
      this.labelDataName.id = ''
      this.isLabelAddModalVisible = false
    },

    // 编辑标签modal
    editLabelRenter (id, name) {
      this.isLabelAddModalVisible = true
      this.labelDataName.id = id
      this.labelDataName.name = name
    },

    // 删除标签
    delLabelRenter () {
      http.request(this, api.tenant_tags_del, [this.delLabelId], null, res => {
        if (res) {
          console.log('删除标签成功', res)
          this.isLabelAddModalVisible = false
          this.getLabelList(1) // 请求标签列表
        }
      })
    },

    // 取消删除标签
    cancelDelLabel () {
      this.delLabelId = ''
    },

    // 保存添加标签
    labelConfirmAddRenter: debounce(function () {
      if (!this.labelDataName.name) {
        this.$Message.error('请输入租客标签名称!')
        return
      }
      let params = {
        name: this.labelDataName.name // 标签名称
      }

      let apiPath

      if (this.labelDataName.id) {
        params.id = this.labelDataName.id
        apiPath = api.tenant_tags_edit
      } else {
        apiPath = api.tenant_tags_add
      }

      http.request(this, apiPath, params.id ? [params.id] : null, params, res => {
        if (res) {
          console.log('添加租客标签成功', res)
          this.isLabelAddModalVisible = false
          this.getLabelList(1) // 请求标签列表
        }
      })
    }, 300),

    resetForm (name) {
      this.$refs[name].resetFields()
    },

    cancelCheckIn () {
      // 关闭入住弹窗
      this.isCheckInVisible = false
    },

    checkInSuccess () {
      // 关闭入住弹窗
      this.isCheckInVisible = false
      this.getRenterList(1)
    },

    // 请求租客列表数据
    getRenterList (page) {
      if (this.isLoadig) {
        return
      }
      if (page === 1) {
        this.currentPage = 1
      }

      this.isLoadig = true
      let params = {
        type: this.selectSearchType || null,
        keyword: this.keyword ? this.keyword : null,
        limit: this.size,
        offset: this.size * (page - 1)
      }

      if (this.tenant_tag_id) {
        params.tenant_tag_id = this.tenant_tag_id
      }

      http.request(this, api.tenant_list, null, params, res => {
        if (res) {
          // res.list.forEach(item => {
          //     if (item.lease) {
          //         // 如果已入住则不可选中删除
          //         item._disabled = true;
          //     }
          // });
          this.renters = res.list
          this.total = res.count || 0
        }
        this.isLoadig = false
      })
    }

  }
}
</script>

<style lang="less">
.renter-list {
    &-title {
        height: auto;
    }
    &-hide {
        display: none;
    }
    &-info {
        padding: 5px 0;
    }
    &-save-succ {
        padding: 20px 0;
        text-align: center;
    }
    &-save-succ .icon {
        font-size: 60px;
    }
    &-save-succ span {
        font-size: 20px;
    }
}

.ivu-tabs-tabpane {
    > div {
        visibility: visible !important;
    }
}

.yd-padding-b-16 {
    padding-bottom: 16px;
}
.export-link {
    color: #fff;
    text-decoration: none;
}
.export-link:hover {
    color: #fff;
}
</style>
